﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 玩家角色枪口位置计算
/// </summary>
public class PlayerMuzzle 
{
    /// <summary>
    /// 取得枪口位置
    /// </summary>
    /// <param name="player">玩家角色对象</param>
    /// <returns>枪口位置和子弹飞行方向</returns>
    public static BulletMeta GetMuzzle(Player player){
        BulletMeta ret=null;
        GameObject bodyPart=null;
        // 子弹发射方向
        Vector2 direction=player.keyDirection;
        // 角色对象作为位置作为基准位置
        Vector2 basePosition=player.transform.position;

        if(player.state==typeof(PlayerStateAction_LieDown)){
            // 卧倒状态子弹只能向左右发射
            direction=new Vector2(player.lookAt.x,0f);
        }else if(player.keyDirection.x==0f && player.keyDirection.y==0f){
            // 如果没有按方向键，采用角色面向的方向作为子弹发射的方向
            direction=player.lookAt;
        }

        // 根据当前状态选择不同的身体部件用来取得Border信息，即枪口位置
        if(player.state==typeof(PlayerStateAction_Normal)){
            bodyPart=player.upperBody;
            // 站立时上半身的位置作为基准位置
            basePosition+=new Vector2(0f,1.1875f);
        }else if(player.state==typeof(PlayerStateAction_Fall)){
            bodyPart=player.fallBody;
        }else if(player.state==typeof(PlayerStateAction_InWater)){
            bodyPart=player.inWaterBody;
        }else if(player.state==typeof(PlayerStateAction_LieDown)){
            bodyPart=player.lieDownBody;
        }else if(player.state==typeof(PlayerStateAction_Roll)){
            bodyPart=player.rollBody;
            {
                //跳跃翻滚时根据子弹发射方向重新计算基准位置
                if(player.rollBody.TryGetComponent(out SpriteRenderer sr)){
                    Bounds bounds=sr.bounds;
                    Vector3 offset=new Vector3(bounds.extents.x*direction.x,bounds.extents.y*direction.y,0);
                    basePosition=bounds.center+offset;
                }
            }
        }

        {
            if(bodyPart!=null && bodyPart.TryGetComponent(out SpriteRenderer sr)){
                ret=new();
                // 根据选定的身体部件确定枪口偏移
                Vector2 sourcePointOffset=GetSpriteMuzzleOffset(sr.sprite);
                // X值需要根据面向方向调整
                sourcePointOffset.x*=player.lookAt.x;
                // 枪口位置=基准位置+枪口偏移量
                ret.sourcePoint=basePosition+sourcePointOffset;
                // 子弹发射方向
                ret.targetPoint=ret.sourcePoint+direction;
            }
        }
        return ret;
    }

    /// <summary>
    /// 通过精灵的Border取得枪口的偏移量
    /// </summary>
    /// <param name="sprite"精灵</param>
    /// <returns>枪口偏移向量</returns>
    private static Vector2 GetSpriteMuzzleOffset(Sprite sprite){
        Bounds bounds= sprite.bounds;
        //X=左边框、Y=下边框、Z=右边框、W=上边框。
        Vector4 border=sprite.border;
        Vector2 ret=new (bounds.max.x,bounds.max.y);
        ret+=-1*border.z*Vector2.right/16f;
        ret+=-1*border.w*Vector2.up/16f;
        return ret;
    }
}